<template>
  <div class="companyOrgMaintain ">
    <div class="companyOrgMaintainBtn">
      <el-button :disabled="isDisabled" type="primary" @click="add">新增</el-button>
    </div>
    <div class="companyOrgMaintainWrap clearfix">
      <!-- 左侧树 -->
      <div class="leftTree">
        <el-tree :data="dataTree" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
      </div>
      <!-- 右侧内容 -->
      <div class="rightContent" v-show="isFirst">
        <!-- <TopFilter
                :list="formList"
                :cols="7"
                :isSubmitBtn="false"
                ></TopFilter> -->
        <FormPanel ref="formPanel" :cols="2" :list="formList" formType="edit" :isSubmitBtn="false" />
        <FilterTable v-if="isShow" ref="table" :columns="columns" :dataSource="dataSource" :isSelectColumn="false" :onCellChange="onCellChange" :onColumnsChange="columns => (this.columns = columns)">
          <!-- <template slot="controls" slot-scope="props">
                    <el-button size="small" type="primary" icon="el-icon-plus" @click="addHandle(props)">新增</el-button>
                </template> -->
        </FilterTable>

        <div class="submit">
          <el-button type="primary" v-show="isShowSubmit" :disabled="isSaveDisabled" @click="submit">保存</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getChildOrgTreeList, getChildOrgdetail, getOrgBrand, getOrgSeries, saveOrgInfo } from '@/api/common/org/companyOrgManage';
import { dictionary } from '@/utils/dictMixin';
import { systemCode} from '@/utils/validate';
export default {
  name: 'companyOrgMaintain',
  mixins: [dictionary],
  data() {
    return {
      isDisArea: '',
      isMerge: '',
      isParent: '',
      orgType: '',
      isShow: false,
      isDisabled: false,
      isSaveDisabled: false,
      isFirst: false,
      isShowSubmit: false,
      dataTree: [],
      defaultProps: {
        children: 'children',
        label: 'text'
      },
      formList: this.createFormList(),
      columns: this.createTableColumns(),
      dataSource: [],
      params: {
        orgId: 0,
        type: 10041002
      },
      BrandData: {
        orgId: 0
      },
      SeriesData: {
        orgId: 0,
        brandId: ''
      },
      OrgInfo: {
        dataType: 0,
        isValid: 0,
        listOBSVO: [],
        orgCode: 'string',
        orgDesc: 'string',
        orgId: 'string',
        orgName: 'string',
        orgType: 0,
        parentOrgCode: 'string',
        parentOrgId: 'string',
        parentOrgName: 'string',
        recordVersion: 0
      },
      addFlag: false,
    };
  },
  mounted() {
    this.getVueTree();
    this.isDisabled = true;
  },
  methods: {
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '上级组织',
          fieldName: 'parentOrgName',
          orgId: 'orgId',
          initialValue: '',
          disabled: true,
          placeholder: '上级组织',
          style: { width: '200px' },
          rules: [{ required: true, message: '请输入上级组织', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '组织代码',
          fieldName: 'orgCode',
          disabled: true,
          placeholder: '组织代码',
          maxlength: 16,
          style: { width: '200px' },
          rules: [
            { required: true, message: '请输入组织代码', trigger: 'change' },
            { min: 1, max: 16, message: '长度在 1 到 16 个字符', trigger: 'blur' },
            { trigger: 'blur',validator: systemCode }
          ]
        },
        {
          type: 'INPUT',
          label: '组织名称',
          fieldName: 'orgName',
          placeholder: '组织名称',
          style: { width: '200px' },
          maxlength: 30,
          rules: [
            { required: true, message: '请输入组织名称', trigger: 'change' },
            { min: 1, max: 30, message: '长度在 1 到 30 个字符', trigger: 'blur' }
          ]
        },
        {
          type: 'SELECT',
          label: '组织类型',
          fieldName: 'orgType',
          // disabled:true,
          disabled: false,
          placeholder: '组织类型',
          itemList: this.createDictList('1506'),
          style: { width: '200px' },
          rules: [{ required: true, message: '请选择组织类型', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '组织状态',
          fieldName: 'isValid',
          initialValue: '',
          placeholder: '组织状态',
          itemList: this.createDictList('1001'),
          style: { width: '200px' },
          rules: [{ required: true, message: '请选择组织状态', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '组织描述',
          fieldName: 'orgDesc',
          placeholder: '组织描述',
          maxlength: 64,
          style: { width: '200px' }
        }
      ];
    },

    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '授权类型',
          dataIndex: 'billType',
          sorter: true,
          filterType: 'input',
          filterItems: [],
          editable: false,
          editType: 'select',
          editItems: this.createDictList('7021')
        },
        {
          title: '授权品牌',
          dataIndex: 'brandId',
          sorter: true,
          filterType: 'input',
          filterItems: [],
          editable: true,
          editType: 'select',
          editItems: []
        },
        {
          title: '授权车系',
          dataIndex: 'seriesId',
          sorter: true,
          filterType: 'input',
          filterItems: [],
          editable: true,
          editType: 'select',
          editItems: []
        }
      ];
    },
    // getVueTree
    getVueTree() {
      this.dataTree = [];
      getChildOrgTreeList(this.params)
        .then(res => {
          this.dataTree.push(res.data[0]);
        })
        .catch(err => {});
    },
    //树节点
    handleNodeClick(data) {
      //addFlag
      this.addFlag = false;

      this.isFirst = true;
      this.formList[0].disabled = true;
      this.formList[1].disabled = true;
      this.formList[3].disabled = true;
      let that = this;

      // 不要调动顺序
      this.isShowSubmit = true;
      this.formList[3].itemList = this.createDictList('1506');
      console.log(data, 'data');
      if (data.parent == 0) {
        this.isDisabled = false;
        this.formList.find(item => item.fieldName == 'orgName').disabled = true;
        this.formList.find(item => item.fieldName == 'isValid').disabled = true;
      } else if (["15061004","15061005","15061006","15061007","15061013","15061014","15061016","15061017","15061019","15061020"].includes(data.orgType)) {
        this.isDisabled = false;
        this.formList.find(item => item.fieldName == 'orgName').disabled = false;
        this.formList.find(item => item.fieldName == 'isValid').disabled = false;
      } else if (["15061015","15061018","15061021"].includes(data.orgType)) {
        this.formList.find(item => item.fieldName == 'orgName').disabled = false;
        this.formList.find(item => item.fieldName == 'isValid').disabled = false;
        this.isDisabled = true;
      }

      this.isParent = data.parent;

      if (data != '' || data != 'undefined') {
        this.params.orgId = data.orgId;
        getChildOrgTreeList(this.params)
          .then(res => {
            data.children = res.data;
          })
          .catch(err => {});

        getChildOrgdetail(this.params)
          .then(res => {
            console.log(res, 'res');
            this.isDisArea = res.data.isDisArea;
            this.isMerge = res.data.isMerge;
            this.orgType = res.data.orgType;
            // 保存传递参数
            that.OrgInfo.dataType = res.data.dataType;
            that.OrgInfo.recordVersion = res.data.recordVersion;
            that.OrgInfo.orgId = res.data.orgId;

            that.OrgInfo.parentOrgId = res.data.parentOrgId;
            that.OrgInfo.parentOrgName = res.data.parentOrgName;

            this.dataSource = res.data.listOBSVO;
            that.formList.forEach(x => {
              if (x.fieldName == 'orgType') {
                x.initialValue = parseInt(res.data[x.fieldName]);
              } else {
                x.initialValue = res.data[x.fieldName];
              }
              x.orgId = res.data.orgId;
            });
            if (!res.data.parentOrgName) {
              console.log(res.data, 'res.data');
              that.formList.find(item => item.fieldName === 'parentOrgName').rules = [];
            } else {
              that.formList.find(item => item.fieldName === 'parentOrgName').rules = { required: true, message: '请输入上级组织', trigger: 'change' };
            }
            if (res.data.parentOrgId == null) {
              res.data.parentOrgId = 0;
            }

            this.getBrandAndSeries(res.data.parentOrgId);
          })
          .catch(err => {});
      } else {
        this.formList.forEach(ele => {
          ele.initialValue = '';
        });
        this.dataSource = [];
      }

    },

    // 获取品牌/车系
    getBrandAndSeries(orgId) {
      //品牌
      this.BrandData.orgId = orgId;
      this.columns[2].editItems = [];
      this.columns[3].editItems = [];
      getOrgBrand(this.BrandData)
        .then(OrgBrand => {
          // console.log(OrgBrand,'OrgBrand')
          OrgBrand.data.forEach(x => {
            this.columns[2].editItems.push({ text: x.brandName, value: x.brandId });
          });
        })
        .catch(err => {});

      // 车系
      this.SeriesData.orgId = orgId;
      this.dataSource.forEach(x => {
        this.SeriesData.brandId = x.seriesId;
      });
      getOrgSeries(this.SeriesData)
        .then(res => {
          // console.log(res,'SeriesData')
          res.data.forEach(x => {
            this.columns[3].editItems.push({ text: x.seriesName, value: x.seriesId });
          });
        })
        .catch(err => {});
    },

    //initTableData
    initTableData() {
      this.dataSource.forEach(ele => {
        if (ele.billType == 70211001) {
          ele.seriesId = '';
        } else {
        }
      });
    },
    //表格数据变化时
    onCellChange(val, val2) {
      console.log(val, val2, 'val');
      console.log(val[Object.keys(val)[0]], '修改后对应的编码');
      if (val[Object.keys(val)[0]] == val2.brandId) {
        this.columns[3].editItems = [];
        this.SeriesData.brandId = val2.brandId;
        getOrgSeries(this.SeriesData)
          .then(res => {
            console.log(res, 'SeriesData');
            res.data.forEach(x => {
              this.columns[3].editItems.push({ text: x.seriesName, value: x.seriesId });
            });
          })
          .catch(err => {});
      }
    },
    //表格新增
    addHandle(props) {
      console.log(props, 'props');
      this.dataSource.push({ index: props.data.length, billType: 70211002 });
    },
    // 新增
    add() {
      if(this.addFlag){
        this.$notify.warning("请先完成当前新增");
        return;
      }
      //addFlag
      this.addFlag = true;

      if(this.formList.find(item => item.fieldName == 'isValid').initialValue == 10011002){
        this.$notify.warning("组织状态无效，无法新增");
        return;
      }

      let that = this;
      this.formList.find(item => item.fieldName == 'orgName').disabled = false;
      this.formList.find(item => item.fieldName == 'isValid').disabled = false;
      this.formList.find(item => item.fieldName == 'isValid').initialValue = 10011001;

      if(this.orgType == 15061001){
        //车厂，新增时组织类型赋值车厂部门/C端战区/B端战区/服务战区（均为二级部门）
        this.formList[3].itemList = [
          { text: '车厂部门', value: 15061004 },
          { text: '零件部门', value: 15061005 },
          { text: '销售部门', value: 15061006 },
          { text: '售后部门', value: 15061007 },
        ];
        that.formList[3].disabled = false;
      }else if (this.orgType == 15061004) {
        //车厂部门，新增时组织类型依然赋值部门不可选
        this.formList[3].itemList = [
          { text: '车厂部门', value: 15061004 },
        ];
        that.formList[3].disabled = false;
      }else if (this.orgType == 15061005) {
        //零件部门，新增时组织类型依然赋值部门不可选
        this.formList[3].itemList = [
          { text: '零件部门', value: 15061005 },
        ];
        that.formList[3].initialValue = 15061005;
        that.formList[3].disabled = true;
      }else if (this.orgType == 15061006) {
        //销售部门，新增时组织类型依然赋值部门不可选
        this.formList[3].itemList = [
          { text: '销售部门', value: 15061006 },
          { text: '销售战区', value: 15061013 },
        ];
        that.formList[3].initialValue = 15061007;
        that.formList[3].disabled = false;
      }else if (this.orgType == 15061007) {
        //售后部门，新增时组织类型依然赋值部门不可选
        this.formList[3].itemList = [
          { text: '售后部门', value: 15061007 },
          { text: '服务战区', value: 15061019 },
        ];
        that.formList[3].initialValue = 15061007;
        that.formList[3].disabled = false;
      }else if (this.orgType == 15061013) {
        //C端战区（销售一级区域），新增时组织类型赋值C端大区（销售二级区域）
        this.formList[3].itemList = [
          { text: '销售大区', value: 15061014 },
        ];
        this.formList[3].initialValue = 15061014;
        this.formList[3].disabled = true;
      }else if (this.orgType == 15061014) {
        //C端大区（销售二级区域），新增时组织类型赋值C端小区（销售三级区域）
        this.formList[3].itemList = [
          { text: '销售小区', value: 15061015 },
        ];
        this.formList[3].initialValue = 15061015;
        this.formList[3].disabled = true;
      }else if (this.orgType == 15061016) {
        //B端战区（销售一级区域），新增时组织类型赋值B端大区（销售二级区域）
        this.formList[3].itemList = [
          { text: 'B端大区', value: 15061017 },
        ];
        this.formList[3].initialValue = 15061017;
        this.formList[3].disabled = true;
      }else if (this.orgType == 15061017) {
        //B端大区（销售二级区域），新增时组织类型赋值B端大区（销售三级区域）
        this.formList[3].itemList = [
          { text: 'B端小区', value: 15061018 },
        ];
        this.formList[3].initialValue = 15061018;
        this.formList[3].disabled = true;
      }else if(this.orgType == 15061019){
        //服务战区（售后一级区域），新增时组织类型赋值服务大区（售后二级区域）
        this.formList[3].itemList = [
          { text: '服务大区', value: 15061020 },
        ];
        this.formList[3].initialValue = 15061020;
        this.formList[3].disabled = true;
      }else if(this.orgType == 15061020){
        //服务大区（售后二级区域），新增时组织类型赋值服务大区（售后三级区域）
        this.formList[3].itemList = [
          { text: '服务小区', value: 15061021 },
        ];
        this.formList[3].initialValue = 15061021;
        this.formList[3].disabled = true;
      }

      console.log(this.isParent, this.orgType, 'this.isParent');

      let parentOrgName = this.formList[2].initialValue;
      console.log(this.formList, 'add');

      this.SeriesData.orgId = this.formList[0].orgId;
      this.OrgInfo.parentOrgId = this.formList[0].orgId;
      this.OrgInfo.orgId = '';
      this.dataSource = [];
      this.formList[0].initialValue = parentOrgName;
      this.formList[0].disabled = true;
      this.formList[1].disabled = false;
      // this.formList[3].disabled=false
      // this.formList[3].itemList=[{'text': "部门",'value': 15061004},{'text': "销售团队",'value': 15061013}]

      this.clearData();
      //新增状态设置为有效
      this.formList.find(item => item.fieldName == 'isValid').initialValue = 10011001;
    },
    //保存
   async submit() {
      let that = this;
      console.log(this.formList, this.dataSource, 'submit');
        let flag = true;
        debugger;
        // this.$refs.formPanel;

      await  this.$refs.formPanel.$refs.form.validate().catch(err => {
          flag = false;
        });
        console.log("flag:",flag);
        if(!flag){
          return;
        }
      this.OrgInfo.listOBSVO = this.dataSource;
      this.OrgInfo.parentOrgCode = this.formList[0].orgId;
      this.OrgInfo.orgCode = this.formList[1].initialValue;
      this.OrgInfo.orgName = this.formList[2].initialValue;
      this.OrgInfo.orgType = this.formList[3].initialValue;
      this.OrgInfo.isValid = this.formList[4].initialValue;
      this.OrgInfo.orgDesc = this.formList[5].initialValue;

      if (this.OrgInfo.parentOrgCode && this.OrgInfo.orgCode && this.OrgInfo.orgName && this.OrgInfo.orgType && this.OrgInfo.isValid) {
        this.isSaveDisabled = true;
        console.log(this.OrgInfo, 'this.OrgInfo');
      let res= await saveOrgInfo(this.OrgInfo)
            console.log(res, 'res');
            if (res.resultCode == 200) {
              this.isSaveDisabled = false;
              this.$message({
                message: `保存成功`,
                type: 'success'
              });
              this.params = {
                orgId: 0,
                type: 10041002
              };
              this.getVueTree();
              this.isFirst = false;
            } else {
              this.isSaveDisabled = false;
              /*  this.$message({
                            message: `${res.errMsg}`,
                            type: 'success'
                        }); */
            }

            this.params = {
              orgId: 0,
              type: 10041002
            };
            // this.clearData()
            //this.getVueTree(this.params)
        }else{
              this.$notify.warning('请将必填项补充完整');
              return;
            }

      //addFlag
      this.addFlag = false;
    },
    //清空处理
    clearData() {
      this.formList.forEach(ele => {
        if (ele.disabled != true) {
          ele.initialValue = '';
        }
      });
    }
  }
};
</script>

<style lang="less" scoped>
.companyOrgMaintain {
  .companyOrgMaintainBtn {
    padding: 10px;
  }
  .submit {
    width: 100%;
    text-align: center;
    padding: 10px;
  }
  .companyOrgMaintainWrap {
    height: 79vh;
    border: 1px solid #000;
    box-sizing: border-box;
    overflow: hidden;
    .leftTree {
      width: 36%;
      height: 100%;
      overflow-x: hidden;
      overflow-y: scroll;
      float: left;
      padding: 10px;
      box-sizing: border-box;
    }

    .rightContent {
      width: 64%;
      height: 100%;
      overflow-x: hidden;
      overflow-y: scroll;
      float: left;
      box-sizing: border-box;
      padding: 10px;
      border-left: 2px solid #eee;
    }
  }
}
</style>
